package top.lywivan.netty.reactor.serialize;


import top.lywivan.netty.reactor.model.RequestData;
import top.lywivan.netty.reactor.model.ResponseData;

import java.io.*;

public class JdkSerializer implements RequestSerializer, ResponseSerializer {
    @Override
    public byte[] encodeRequest(RequestData request) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream obs = new ObjectOutputStream(bos);
            obs.writeObject(request);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public RequestData decodeRequest(byte[] bytes) {
        RequestData request = new RequestData();
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            request = (RequestData)ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return request;
    }

    @Override
    public byte[] encodeResponse(ResponseData responseData) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream obs = new ObjectOutputStream(bos);
            obs.writeObject(responseData);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public ResponseData decodeResponse(byte[] bytes) {
        ResponseData responseData = new ResponseData();
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            responseData = (ResponseData)ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return responseData;
    }
}
